package com.sportizz.sport;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.sportizz.model.sports;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.PorterDuff.Mode;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class sport_follow_class extends Activity {

	// List<String> sport_adp;
	SelectionAdapter sport_adapter;

	ListView lv;
	public ProgressDialog pd = null;

	Button btn_done;
	DatabaseAdapter dataAdapter;
	Context context;

	List<sports> sport_adp;
	sports sport;
	public int list_count = 0;
	String email, device_id, country_code;
	boolean tablet;
	public static Activity sport_act;

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sport_follow);

		sport_act = this;

		Intent i = getIntent();

		StartActivity.is_app_start = true;

		country_code = i.getStringExtra("country_code");
		email = i.getStringExtra("email");
		device_id = i.getStringExtra("device_id");
		tablet = i.getBooleanExtra("istablet", false);

		lv = (ListView) findViewById(R.id.sp_follow_list);

		btn_done = (Button) findViewById(R.id.btn_done_sp_follow);
		context = this;

		sport_adp = new ArrayList<sports>();

		// sport_adp = new ArrayList<String>();

		sport_adapter = new SelectionAdapter(this, sport_adp);

		dataAdapter = new DatabaseAdapter(this);
		// dataAdapter.open();

		
		
		
		btn_done.setEnabled(false);
		lv.setAdapter(sport_adapter);
		lv.setDividerHeight(1);
		lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		AsyncTask<Void, Void, Void> wait1 = new AsyncTask<Void, Void, Void>() {

			@Override
			protected void onPostExecute(Void result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				pd.dismiss();

				sport_adapter.notifyDataSetChanged();
				
//				dataAdapter.close();
			}

			@Override
			protected void onPreExecute() {
				pd = ProgressDialog.show(sport_follow_class.this, "", "", true);
				super.onPreExecute();
			}

			@Override
			protected Void doInBackground(Void... params) {

				dataAdapter.open();
				
				Cursor c=dataAdapter.getcolumnName();
				String[] cName = c.getColumnNames();
				dataAdapter.close();
				
				for(int a=0;a<cName.length;a++)
				{
					Log.i("new_version","ColNAme = "+ cName[a]);
				}
				
				try {
					String sportjson = Utils
							.readJsonFeed(
									"http://sportizza.com/interface/ios_sport_list.php",
									sport_follow_class.this);
					// StartActivity.newsport_name = new HashMap<String,
					// String>();
					// StartActivity.gl_sport_list = new ArrayList<String>();
					// StartActivity.newsport_code=new HashMap<String,
					// String>();

					if (sportjson == null || sportjson.equals("null")) {
						com.sportizz.sport.AlertDialogManager alert = new com.sportizz.sport.AlertDialogManager();
						alert.showAlertDialog(sport_follow_class.this,
								"Connection Problem",
								"Please check internet connection..", false);
						finish();

					} else {
						JSONArray array_sports = null;

						array_sports = new JSONArray(sportjson);

						int array_len1 = array_sports.length();

						dataAdapter.open();
						dataAdapter.deleteSportdata();
						dataAdapter.close();

						for (int i = 0; i < array_len1; i++) {

							JSONObject JsonObject_sport = array_sports
									.getJSONObject(i);

							String ss_sport = JsonObject_sport
									.getString("ss_sport");

							String ss_sport_code = JsonObject_sport
									.getString("ss_sport_code");

							String ss_team_sport = JsonObject_sport
									.getString("ss_team_sport");

							sport = new sports();

							sport.setName(ss_sport);
							sport.setCode(ss_sport_code);
							sport_adp.add(sport);

							// sport_adp.add(get(ss_sport + ":" +
							// ss_sport_code));

							// StartActivity.gl_sport_list.add(ss_sport+":"+ss_sport_code);
							// StartActivity.newsport_name.put(ss_sport,
							// ss_sport_code
							// + ":" + ss_team_sport);
							// StartActivity.newsport_code.put(ss_sport_code,ss_sport);

							dataAdapter.open();
							dataAdapter.insertSportdata(ss_sport,
									ss_sport_code, ss_team_sport);
							dataAdapter.close();

						}
					}

					// dataAdapter.open();
					// Cursor cc=dataAdapter.getsportlist();
					//
					// cc.moveToFirst();
					//
					// while(cc.moveToNext())
					// {
					// Log.d("suraj_","cc == "+cc.getString(cc.getColumnIndex("sport")));
					// }
					// dataAdapter.close();

					// Log.d("suraj", "StartActivity.newsport_name = "
					// + StartActivity.newsport_name);
					// lv.setAdapter(null);
					// lv.setVisibility(View.VISIBLE);

				} catch (Exception e) {
					e.printStackTrace();

					new Thread(new Runnable() {

						@Override
						public void run() {

							runOnUiThread(new Runnable() {

								@Override
								public void run() {

									AlertDialog.Builder build = new AlertDialog.Builder(
											sport_follow_class.this);
									build.setCancelable(false);
									build.setTitle("Check Internet Connection..");
									build.setPositiveButton(
											"Yes",
											new DialogInterface.OnClickListener() {
												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													dialog.dismiss();
												}
											});

									AlertDialog alert = build.create();
									alert.show();

									// return null;

								}
							});

						}
					});

				}
				return null;
			}
		};
		wait1.execute();

		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// TextView sportName = (TextView) view
				// .findViewById(R.id.sportName);
				// ImageView image_sport_ = (ImageView) view
				// .findViewById(R.id.image_sport_);
				CheckBox image_follow = (CheckBox) view
						.findViewById(R.id.image_follow);

				sports bean = sport_adp.get(position);

				if (bean.isSelected()) {
					bean.setSelected(false);
					image_follow.setChecked(false);

					if (list_count == 0) {
						btn_done.setEnabled(false);
					}

				} else {
					btn_done.setEnabled(true);
					bean.setSelected(true);
					image_follow.setChecked(true);
				}

			}
		});

		btn_done.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				AsyncTask<Void, Void, Void> wait = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... arg0) {

						StringBuffer sb = new StringBuffer();

						// Retrive Data from list
						for (sports bean : sport_adp) {

							if (bean.isSelected()) {
								sb.append(bean.getName());
							}
						}

						if (list_count != 0) {
							Intent intent = new Intent(sport_follow_class.this,
									MainActivity.class);
							intent.putExtra("country_code", country_code);
							intent.putExtra("email", email);
							intent.putExtra("device_id", device_id);
							intent.putExtra("istablet", tablet);

							startActivity(intent);
						}

						return null;
					}

				};
				wait.execute();
			}
		});

	}

	@Override
	protected void onDestroy() {
		StartActivity.first_act.finish();
		android.os.Process.killProcess(android.os.Process.myPid());
		finish();
		super.onDestroy();
	}

	@Override
	protected void onStop() {
		StartActivity.first_act.finish();
		android.os.Process.killProcess(android.os.Process.myPid());
		finish();
		super.onStop();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Do You Want to Close the Application")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									setResult(200);

									dialog.dismiss();

									StartActivity.first_act.finish();
									android.os.Process
											.killProcess(android.os.Process
													.myPid());
									finish();
								}

							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
			setResult(RESULT_CANCELED);

			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	private class SelectionAdapter extends ArrayAdapter<sports> {

		private final List<sports> list;
		private final Context context_;
		public final List<String> ArrFDItem = null;

		public SelectionAdapter(Context context, List<sports> sport_adp) {
			super(context, R.layout.sport_follow_menu, sport_adp);
			this.context_ = context;
			this.list = sport_adp;
		}

		class ViewHolder {
			protected TextView sportName;
			protected ImageView image_sport_;
			protected CheckBox image_follow;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			View view;
			final ViewHolder viewHolder;

			if (convertView == null) {
				LayoutInflater inflator = sport_follow_class.this
						.getLayoutInflater();
				view = inflator.inflate(R.layout.sport_follow_menu, null);
				viewHolder = new ViewHolder();
				viewHolder.sportName = (TextView) view
						.findViewById(R.id.sportName);
				viewHolder.image_sport_ = (ImageView) view
						.findViewById(R.id.image_sport_);
				viewHolder.image_follow = (CheckBox) view
						.findViewById(R.id.image_follow);
				viewHolder.image_follow
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {

							@Override
							public void onCheckedChanged(CompoundButton view,
									boolean isChecked) {
								sports element = (sports) viewHolder.image_follow
										.getTag();
								element.setSelected(view.isChecked());

								if (view.isChecked()) {
									list_count++;
									viewHolder.sportName
											.setTextColor(Color.parseColor("#FFCC11"));
									viewHolder.image_sport_
											.setColorFilter(Color.parseColor("#FFCC11"));

									dataAdapter.open();

									String sport_data = dataAdapter
											.getsportcodelist(viewHolder.sportName
													.getText().toString());

									// String sport =
									// dataAdapter.getsportname(sport_data);
									// String[] ss=sport_data.split(":");

									dataAdapter.insert_follow_info(sport_data,
											null, null, viewHolder.sportName
													.getText().toString(),
											null, null, "s");
									dataAdapter.close();
								} else {
									list_count--;
									Resources res = getResources();
									int color = res.getColor(R.color.da_gray);
									viewHolder.sportName.setTextColor(color);
									viewHolder.image_sport_
											.setColorFilter(Color.WHITE);

									dataAdapter.open();
									String sport_data = dataAdapter
											.getsportcodelist(viewHolder.sportName
													.getText().toString());
									dataAdapter.deletesportValue(sport_data,
											"s");
									dataAdapter.close();

								}
							}
						});

				view.setTag(viewHolder);
				viewHolder.image_follow.setTag(list.get(position));
				viewHolder.sportName.setTag(list.get(position));
				viewHolder.image_sport_.setTag(list.get(position));
			} else {
				view = convertView;

				((ViewHolder) view.getTag()).image_follow.setTag(list
						.get(position));
				((ViewHolder) view.getTag()).sportName.setTag(list
						.get(position));
				((ViewHolder) view.getTag()).image_sport_.setTag(list
						.get(position));
			}

			ViewHolder holder = (ViewHolder) view.getTag();
			holder.sportName.setText(list.get(position).getName());
			holder.image_sport_.setImageBitmap(bitmap_image(list.get(position)
					.getCode()));
			holder.image_follow.setChecked(list.get(position).isSelected());
			return view;
		}
	}

	private Bitmap bitmap_image(String image_code) {
		InputStream is1;
		Bitmap output1 = null;
		try {
			is1 = context.getResources().getAssets()
					.open("sports/" + image_code + ".png");

			Bitmap res1 = BitmapFactory.decodeStream(is1);

			// Log.i("suraj", "champ =" + res1);

			output1 = Bitmap.createBitmap(res1.getWidth(), res1.getHeight(),
					Bitmap.Config.ARGB_8888);
			Canvas canvas1 = new Canvas(output1);

			Paint paint = new Paint();
			Rect rect = new Rect(0, 0, res1.getWidth(), res1.getHeight());
			RectF rectF = new RectF(rect);
			float roundPx1 = 8f;

			paint.setAntiAlias(true);
			canvas1.drawARGB(0, 0, 0, 0);
			paint.setColor(0xff424242);
			canvas1.drawRoundRect(rectF, roundPx1, roundPx1, paint);
			paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
			canvas1.drawBitmap(res1, rect, rect, paint);
		} catch (Exception e) {
			try {
			is1 = context.getResources().getAssets()
					.open("sports/GAM.png");

			Bitmap res1 = BitmapFactory.decodeStream(is1);

			// Log.i("suraj", "champ =" + res1);

			output1 = Bitmap.createBitmap(res1.getWidth(), res1.getHeight(),
					Bitmap.Config.ARGB_8888);
			Canvas canvas1 = new Canvas(output1);

			Paint paint = new Paint();
			Rect rect = new Rect(0, 0, res1.getWidth(), res1.getHeight());
			RectF rectF = new RectF(rect);
			float roundPx1 = 8f;

			paint.setAntiAlias(true);
			canvas1.drawARGB(0, 0, 0, 0);
			paint.setColor(0xff424242);
			canvas1.drawRoundRect(rectF, roundPx1, roundPx1, paint);
			paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
			canvas1.drawBitmap(res1, rect, rect, paint);
			}catch (Exception e1) {
			}
		}
		return output1;
	}
}
